from chapter import Chapter
from os import path 
import pickle

class Book:
    def __init__(self,url,save_path=None) -> None:
        super().__init__()
        self.title=None
        self.chapter_count=None
        self.url=url
        self.save_path=save_path
        self.chapters=dict()
        # self.completed=False

    def is_completed(self):
        # if len(self.chapters) < self.chapter_count:
        #     return False
        if self.is_missing_chapter():
            return False
        for chapter in self.chapters.values():
            if chapter.is_completed()==False:
                return False
        return True
    
    def is_missing_chapter(self):
        return not self.chapter_count or len(self.chapters) < self.chapter_count
    
    def add_chapter(self,chapter:Chapter):
        chapter.chapter_folder=path.join(self.get_book_folder(),chapter.title)
        self.chapters[chapter.title]=chapter
    
    def get_chapter(self,chapter_title):
        return self.chapters.get(chapter_title,None)
    
    def has_chapter(self,chater_title):
        return chater_title in self.chapters
    
    def get_book_folder(self):
        if not self.title:
            raise Exception('漫画名称未设置!')
        if not self.save_path:
            return self.title
        else:
            return path.join(self.save_path,self.title)
    
    # def scan_chapter_progress(self):
    def __getstate__(self):
        state=self.__dict__.copy()
        chapters=self.chapters.values()
        state['chapters']=[chapter.to_dict() for chapter in chapters]
        return state
    
    def __setstate__(self,state):
        chapters=state['chapters']
        state['chapters']={}
        self.__dict__.update(state)

        for chapter in chapters:
            ch=Chapter.from_dict(chapter)
            self.add_chapter(ch)
        return state

    def save(self):
        book_path=path.join(self.get_book_folder(),'book.dat')        
        with open(book_path,'wb') as f:
            pickle.dump(self,f)
    
    @staticmethod
    def load(book_path:str):
        if book_path.endswith('book.dat') ==False:
            book_path=path.join(book_path,'book.dat')
        with open(book_path,'rb') as f:
            return pickle.load(f)


    
    
